package www.bwsensing.com.common.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import www.bwsensing.com.common.CollectionService;
import www.bwsensing.com.common.netty.initializer.NettyTcpInitializer;
import www.bwsensing.com.common.utills.NetworkInterfaceUtil;

/**
 * @author 朱永杰
 */
@Slf4j
@Data
public class NettyTcpServerImpl implements CollectionService {

    private Integer port;

    private NettyTcpInitializer nettyServerInitializer;

    private EventLoopGroup parentGroup = new NioEventLoopGroup();
    private EventLoopGroup childGroup = new NioEventLoopGroup();

    public NettyTcpServerImpl(Integer port, NettyTcpInitializer nettyServerInitializer) {
        this.port = port;
        this.nettyServerInitializer = nettyServerInitializer;
    }

    @Override
    public void start() {
        ServerBootstrap httpBootstrap = new ServerBootstrap();;
        try {
            httpBootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(nettyServerInitializer);
            // 服务器绑定端口监听
            ChannelFuture channelHttp = httpBootstrap.bind(port).sync();
            log.info("TCP服务监听端口启动成功，端口为:{}", port);
            channelHttp.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭EventLoopGroup，释放掉所有资源包括创建的线程
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }

    @Override
    public void stop() {
        childGroup.shutdownGracefully();
        parentGroup.shutdownGracefully();
        if (!NetworkInterfaceUtil.isLocalPortUsing(port)){
            log.info("UDP服务监听端口关闭成功，端口为:{}", port);
        }
    }
}
